<?php

defined("SYSPATH") or die("No direct script access.");

class Controller_File_Upload extends Controller {

	public function action_index() {
		$this->view = Smarty_View::factory("file/file.tpl");
		$this->view->filename = (isset($_GET["filename"])) ? trim($_GET["filename"]) : "";
		$this->view->field = (isset($_GET["field"])) ? trim($_GET["field"]) : "";
		$this->view->uploaded_file = (isset($_GET["uploaded_file"])) ? trim($_GET["uploaded_file"]) : "";
		$this->view->width = (isset($_GET["width"])) ? intval($_GET["width"]) : "";
		$this->view->height = (isset($_GET["height"])) ? intval($_GET["height"]) : "";
		$this->view->max_size = (isset($_GET["max_size"])) ? intval($_GET["max_size"]) : "";
		$this->view->uploaded_function = (isset($_GET["uploaded_function"])) ? trim($_GET["uploaded_function"]) : "file_uploaded";
		$this->response->body($this->view);
	}

	public function action_load() {
		$diretory_tmp = $_SERVER["DOCUMENT_ROOT"] . $this->doc_root . "static/images/tmp/";
		try {
			$filename = "static/images/tmp/" . $_FILES["file"]["name"];
			if (isset($_FILES["file"]) && isset($_POST["field"])) {

				if(isset($_POST["max_size"]) && $maxsize=intval($_POST["max_size"]) && $filesize<$_FILES["file"]["size"]) {
					throw new Kohana_Exception(__("File size is too large (:file_size) max allowed is ::max_size ",array(":file_size"=>$_FILES["file"]["size"],":max_size"=>$maxsize) ) );
				} else {
					if(move_uploaded_file($_FILES["file"]["tmp_name"], DOCROOT . $filename)) {
						chmod(DOCROOT . $filename, 0755);
						if ((isset($_POST["width"]) && intval($_POST["width"])) && (isset($_POST["height"]) && intval($_POST["height"]))) {
							$img = new Image_GD(DOCROOT . $filename);
							$img->resize(intval($_POST["width"]), intval($_POST["height"]));
							$img->save();
						}
					}
				}

				Request::current()->redirect("file/upload/index?field=" . $_POST["field"] . "&uploaded_file=$filename".(isset($_POST["width"]) && intval($_POST["width"]) && isset($_POST["height"]) && intval($_POST["height"])?"&width=".intval($_POST['width'])."&height=".intval($_POST['height']):""));
			}else{
				throw new Kohana_Exception(__("Couldn't find file and field"));
			}
		} catch (Kohana_Exception $e) {
			$this->response->body(print_r($e, true));
		}
	}
	
}

// End File